const url_config = require('../../common/config');
var that;
var app = getApp();
var versionCompareRes = 1;
var recordTimer = null;
const recorderManager = wx.getRecorderManager();
const options = {
  duration: 60000,
  sampleRate: 12000,
  numberOfChannels: 1,
  encodeBitRate: 24000,
  format: 'mp3',
};
let innerAudioContext = null,
  isRecordPlaying = false;
let cid = '';
let fromType = '';
var timer = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSubmitting: false, //是否正在提交数据（控制蒙层的显示和隐藏）
    qDesc: '', //问题描述
    pics: [
      '../../images/icon_addpic.png'
    ],
    picItemWidth: 750,
    couldRecord: false,
    recordState: 0, //0：未开始 1正在录音 2录音暂停  3录音结束
    recordSeconds: 0, //录音秒数
    recordRes: {
      duration: 0,
      fileSize: 0,
      tempFilePath: ''
    },
    spreakingAnimation: {}, //放大动画
    j: 1, //帧动画初始图片
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    console.log(options);
    let topName = options.topName;
    let secondName = options.secondName;
    wx.setNavigationBarTitle({
      title: secondName + "(" + topName + ")"
    })
    cid = options.cid;
    fromType = options.fromType;
    //定时器初始化
    recordTimer = null;
    timer = null;

    wx.getSystemInfo({
      success(res) {
        console.log(res.windowWidth)
        that.setData({
          picItemWidth: (res.windowWidth - 60) / 3
        });

        versionCompareRes = app.compareVersion('1.4.4', res.SDKVersion);

        if (versionCompareRes > 0) {
          //说明当前的微信sdk版本小于1.4.4
          // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
          wx.showModal({
            title: '提示',
            content: '当前微信版本过低，请升级到最新微信版本后重试。'
          })
        }
        let couldRecord = app.compareVersion('1.7.1', res.SDKVersion) <= 0 ? true : false;
        that.setData({
          couldRecord: couldRecord
        })
      }
    });

    //录音初始化
    that.initRecord();
  },

  // 问题描述输入监听
  onQdescInput: function(e) {
    let value = e.detail.value;
    that.setData({
      qDesc: value
    })
  },

  chooseImage: function(e) {
    let picList = that.data.pics;
    if (picList.length > 6) {
      wx.showModal({
        title: '提示',
        content: '最多可上传6张照片',
      })
      return;
    }
    wx.chooseImage({
      count: 7 - picList.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let pics = that.data.pics;
        let addPicIndex = pics.length - 1;
        let addPic = pics[addPicIndex];
        pics.splice(addPicIndex, 1);
        that.setData({
          pics: pics.concat(res.tempFilePaths).concat(addPic)
        });
      }
    })
  },
  //图片点击触发的事件
  onImageClick: function(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index;
    let picId = e.currentTarget.dataset.id;
    wx.showActionSheet({
      itemList: ['查看大图', '删除图片'],
      success(res) {
        if (res.tapIndex == 0) {
          //查看大图
          that.previewImage(picId);
        } else if (res.tapIndex == 1) {
          //删除图片
          that.deleteImg(index);
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },

  // 删除图片
  deleteImg: function(index) {
    var pics = that.data.pics;
    pics.splice(index, 1);
    this.setData({
      pics: pics
    });
  },
  previewImage: function(picId) {
    console.log(picId)
    let images = that.data.pics;

    let imgs_preview = [];
    for (let i = 0; i < images.length; i++) {
      if (i < (images.length - 1)) {
        imgs_preview[i] = images[i];
      }
    }
    console.log(imgs_preview)
    wx.previewImage({
      current: picId, // 当前显示图片的http链接
      urls: imgs_preview // 需要预览的图片http链接列表
    })
  },

  initRecord: function() {
    //播放器初始化
    isRecordPlaying = false;
    innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.onEnded(function() {
      isRecordPlaying = false;
      console.log('onEnded');
    });
    innerAudioContext.onError(function() {
      isRecordPlaying = false;
      wx.showToast({
        title: '播放失败，请重试',
      })
    });


    recorderManager.onPause(() => {
      that.stopRecord();
    })
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      that.data.recordRes = res;
    });
    recorderManager.onError((errMsg) => {
      console.log(errMsg);
    })
  },

  startRecord: function() {
    //开启动画
    that.startSpeak();
    recorderManager.start(options);
    that.setData({
      recordState: 1,
    });
    that.startRecordTimer();
  },
  stopRecord: function() {
    if (timer) {
      clearInterval(timer)
    }
    recorderManager.stop();
    if (recordTimer) {
      clearInterval(recordTimer);
    }
    if (that.data.recordSeconds < 3) {
      that.setData({
        recordState: 0,
        recordSeconds: 0
      });
      wx.showModal({
        title: '提示',
        content: '录制时间太短，不能低于3s',
      })
    } else {
      that.setData({
        recordState: 3,
      });
    }
  },

  startRecordTimer: function() {
    if (recordTimer) {
      clearInterval(recordTimer);
    }
    recordTimer = setInterval(function() {
      let seconds = that.data.recordSeconds;
      //60
      if (seconds > 59) {
        recorderManager.stop();
        if (recordTimer) {
          clearInterval(recordTimer);
        }
        that.setData({
          recordState: 3,
        });
      } else {
        that.setData({
          recordSeconds: ++seconds
        })
      }

    }, 1000);
  },
  //播放录音
  playRecord: function() {
    if (isRecordPlaying) {
      wx.showToast({
        title: '已暂停',
      })
      console.log('pause');
      innerAudioContext.pause();
      isRecordPlaying = false;
      return;
    }
    let voice_url_local = that.data.recordRes.tempFilePath;
    console.log(voice_url_local);
    if (voice_url_local) {
      innerAudioContext.src = voice_url_local; // 这里可以是录音的临时路径
      isRecordPlaying = true;
      console.log('play');
      wx.showToast({
        title: '正在播放',
      })
      innerAudioContext.play();
    }
  },

  //重新录制
  resetRecord: function() {
    wx.showModal({
      title: '提示',
      content: '您确定要重新录制吗？',
      confirmText: '重新录制',
      success: function(res) {
        if (res.confirm) {
          //1.如果在播放的话，停止播放
          innerAudioContext.stop();
          isRecordPlaying = false;
          //2.给data中的录音url赋值为空,改变录音的状态,初始化录音时长
          that.data.recordRes
          that.setData({
            recordState: 0,
            recordSeconds: 0,
            recordRes: {
              duration: 0,
              fileSize: 0,
              tempFilePath: ''
            }
          });
        }
      }
    })
  },

  //提交问题
  askQuestion: function() {
    that.setData({
      isSubmitting: true
    })
    wx.showLoading({
      title: '正在提交问题',
    });
    //判断输入内容至少要填写一项
    let qDesc = that.data.qDesc.trim();
    let is_qimgs = that.data.pics.length > 1;
    let is_qrecord = that.data.recordRes.tempFilePath;
    if (!qDesc && !is_qimgs && !is_qrecord) {
      wx.showModal({
        title: '提示',
        content: '请您至少输入问题描述、图片、语音中的其中一项',
      });
      that.setData({
        isSubmitting: false
      });
      wx.hideLoading();
      return;
    }
    if (versionCompareRes <= 0) {
      //这里的操作是提醒用户去登陆（其实是获取用户头像昵称等资料信息）
      app.getUserinfoByCode(function(userInfo) {
        if (!userInfo.nick_name || !userInfo.head_img) {
          that.setData({
            isSubmitting: false
          })
          wx.hideLoading();
          wx.navigateTo({
            url: '../login/login',
          })
        } else {
          that.doAskQuestion();
        }
      });
    } else {
      that.doAskQuestion();
    }
  },

  doAskQuestion: function() {
    console.log('askQuestion');
    let params = {
      cid: cid,
      qdesc: that.data.qDesc,
      qimgs: '',
      qrecord: '',
    };

    //上传图片
    that.uploadSelectImgs(function(net_imgs) {
      if (net_imgs === false) {
        //说明图片上传失败
        wx.showModal({
          title: '提示',
          content: '图片上传失败',
        })
        that.setData({
          isSubmitting: false
        });
        wx.hideLoading();
      } else {
        params.qimgs = net_imgs;
        //上传语音
        that.uploadRecordFiles(function(net_record) {
          if (net_record === false) {
            //说明图片上传失败
            wx.showModal({
              title: '提示',
              content: '语音上传失败',
            })
            that.setData({
              isSubmitting: false
            });
            wx.hideLoading();
          } else {
            params.qrecord = net_record;
            that.askQuestionRequest(params);
          }
        });
      }

    });
  },



  //最终的网络请求
  askQuestionRequest: function(params) {
    wx.request({
      url: url_config.url_question_ask,
      data: params,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'uidusernamekey': app.globalData.userInfo.token
      },
      success: function(res) {
        let resData = res.data;
        console.log(resData);
        if (resData.status != 200) {
          wx.showModal({
            title: '提示',
            content: resData.message,
          })
          that.setData({
            isSubmitting: false
          });
        } else {
          if (fromType == 'microWx') {
            wx.navigateBack({
              delta: 1
            })
          } else {
            wx.redirectTo({
              url: '../index/index',
            })
          }

        }
        wx.hideLoading();
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: '网络异常',
        })
        that.setData({
          isSubmitting: false
        });
        wx.hideLoading();
      },
    })
  },


  //上传图片
  uploadSelectImgs: function(cb) {
    let images = that.data.pics;
    if (images.length > 1) {
      let imgs_upload = [];
      for (let i = 0; i < images.length; i++) {
        if (i < (images.length - 1)) {
          imgs_upload[i] = images[i];
        }
      }
      //上传图片
      that.uploadImage(0, imgs_upload, function(netUrls) {
        typeof cb == "function" && cb(netUrls);
      }, []);
    } else {
      typeof cb == "function" && cb([]);
    }
  },

  //网络上传语音
  uploadRecordFiles: function(cb) {
    let recordFile = that.data.recordRes.tempFilePath;
    if (!recordFile) {
      typeof cb == "function" && cb('');
      return;
    }
    wx.uploadFile({
      url: url_config.url_uploadRecordFile,
      filePath: recordFile,
      name: 'record',
      success: function(res) {
        let resData = res.data;
        resData = JSON.parse(resData);
        console.log(resData)
        let recordPath = resData.data.path;
        if (resData.status == 200 && recordPath) {
          that.data.recordRes.tempFilePath = recordPath;
          typeof cb == "function" && cb(JSON.stringify(that.data.recordRes));
        } else {
          typeof cb == "function" && cb(false);
        }
      },
      fail: function() {
        console.log(res);
        typeof cb == "function" && cb(false);
      }
    });
  },
  //循环上传图片
  uploadImage: function(index, imgs_upload, cb, netUrls) {
    if (index > imgs_upload.length - 1) {
      typeof cb == "function" && cb(netUrls)
      return;
    }
    wx.uploadFile({
      url: url_config.url_question_uploadImage,
      filePath: imgs_upload[index],
      name: 'img',
      success: function(res) {
        let resData = res.data;
        resData = JSON.parse(resData);
        console.log(resData)
        if (resData.status == 200) {
          netUrls.push(resData.data.imgPath);
          index++;
          that.uploadImage(index, imgs_upload, cb, netUrls);
        } else {
          typeof cb == "function" && cb(false)
        }
      },
      fail: function() {
        typeof cb == "function" && cb(false)
      }
    });
  },

  //捕获表单提交的formid
  onFormItemClick: function(e) {
    console.log(e);
    if (e && e.detail && e.detail.formId) {
      //将formid添加到app globalData中
      let formid = e.detail.formId;
      app.uploadFormId(formid);
    }
  },
  //点击开始说话
  startSpeak: function() {
    that.speaking();
    that.bolang();
    // var _this = this;
    // if (!this.data.isSpeaking) {
    //   speaking.call(this);
    //   this.setData({
    //     isSpeaking: true
    //   })
    // } else {
    //   //去除帧动画循环
    //   clearInterval(this.timer)
    //   this.setData({
    //     isSpeaking: false,
    //     j: 1
    //   })
    // }
  },
  onUnload: function() {
    if (isRecordPlaying) {
      innerAudioContext.pause();
      isRecordPlaying = false;
    }
  },
  speaking: function() {
    //话筒帧动画
    var i = 1;
    that.timer = setInterval(function() {
      i++;
      i = i % 5;
      that.setData({
        j: i
      })
      return
    }, 200);
  },

  bolang: function() {
    console.log('--');
    //波纹放大,淡出动画
    var animation = wx.createAnimation({
      duration: 1000
    })
    animation.opacity(0).scale(3, 3).step(); //修改透明度,放大
    that.setData({
      spreakingAnimation: animation.export()
    })
    setTimeout(function() {
      //波纹放大,淡出动画
      var animation = wx.createAnimation({
        duration: 1000
      })
      animation.opacity(0).scale(3, 3).step(); //修改透明度,放大
      that.setData({
        spreakingAnimation_1: animation.export()
      })
    }, 250)
    setTimeout(function() {
      //波纹放大,淡出动画
      var animation = wx.createAnimation({
        duration: 1000
      })
      animation.opacity(0).scale(3, 3).step(); //修改透明度,放大
      that.setData({
        spreakingAnimation_2: animation.export()
      })
    }, 500)
  }
})